package com.gomyb.admin.core.shiro;

import com.gomyb.redis.RedisService;
import com.gomyb.admin.core.shiro.util.ShiroUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

import java.util.Collection;
import java.util.Set;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 权限缓存控制器
 */
@Log4j2
public class RedisCache<K, V> implements Cache<K, V> {

    private RedisService redisService;

    RedisCache(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * 获得缓存对象
     */
    @Override
    public V get(K key) throws CacheException {
        try {
            V val = redisService.getObj(ShiroUtil.SHIRO_CACHE_PREFIX + key);
            if (null != val) {
                return val;
            }
        } catch (Exception e) {
            log.error(this.getClass(), e);
        }
        return null;
    }

    /**
     * 将权限加入缓存
     */
    @Override
    public V put(K key, V value) throws CacheException {
        try {
            redisService.setObj(ShiroUtil.SHIRO_CACHE_PREFIX + key, value);
            return value;
        } catch (Exception e) {
            log.error(this.getClass(), e);
        }
        return null;
    }

    /**
     * 从缓存中删除权限
     *
     * @param key
     * @return
     * @throws CacheException
     */
    @Override
    public V remove(K key) throws CacheException {
        try {
            if (null != key && !"".equals(key)) {
                String v = redisService.get(ShiroUtil.SHIRO_CACHE_PREFIX + key);
                redisService.del(ShiroUtil.SHIRO_CACHE_PREFIX + key);
                return (V) v;
            }
        } catch (Exception e) {
            log.error(this.getClass(), e);
        }
        return null;
    }

    /**
     * 清空权限缓存
     */
    @Override
    public void clear() throws CacheException {
        redisService.delAll(ShiroUtil.SHIRO_CACHE_PREFIX+"*");
    }

    /**
     * 权限数量
     */
    @Override
    public int size() {
        return redisService.keySize(ShiroUtil.SHIRO_CACHE_PREFIX+"*");
    }

    /**
     * 所有的权限key
     */
    @Override
    public Set<K> keys() {
        return (Set<K>) redisService.keys(ShiroUtil.SHIRO_CACHE_PREFIX+"*");
    }

    /**
     * 所有的权限value
     */
    @Override
    public Collection<V> values() {
        return (Collection<V>) redisService.values(ShiroUtil.SHIRO_CACHE_PREFIX+"*");
    }
}
